import React, { useState } from 'react';
import { Form, Input, Button, Card, message, Modal } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import api from '../api';

const Login = () => {
  const navigate = useNavigate();
  const [registerVisible, setRegisterVisible] = useState(false);
  const [registerForm] = Form.useForm();

  const onFinish = async (values) => {
    // ====== 开发测试用：跳过后端登录，直接写入token，后端接口准备好后请删除此处 ======
    localStorage.setItem('token', 'test-token');
    message.success('开发测试：已跳过登录，直接进入主页面');
    navigate('/dashboard');
    // ====== 真实登录逻辑如下，后端接口准备好后请恢复 ======
    // try {
    //   const res = await api.post('/login', values);
    //   localStorage.setItem('token', res.data.token);
    //   message.success('登录成功！');
    //   navigate('/dashboard');
    // } catch {
    //   message.error('用户名或密码错误！');
    // }
  };

  // 注册提交
  const onRegister = async (values) => {
    try {
      await api.post('/register', values);
      message.success('注册成功，请登录！');
      setRegisterVisible(false);
      // 注册成功后自动登录
      const res = await api.post('/login', values);
      localStorage.setItem('token', res.data.token);
      navigate('/dashboard');
    } catch {
      message.error('注册失败，用户名可能已存在！');
    }
  };

  return (
    <div style={{ 
      height: '100vh', 
      display: 'flex', 
      justifyContent: 'center', 
      alignItems: 'center',
      background: '#f0f2f5'
    }}>
      <Card style={{ width: 400, boxShadow: '0 4px 8px rgba(0,0,0,0.1)' }}>
        <h2 style={{ textAlign: 'center', marginBottom: 24 }}>卒中诊断系统</h2>
        <Form
          name="login"
          onFinish={onFinish}
          autoComplete="off"
        >
          <Form.Item
            name="username"
            rules={[{ required: true, message: '请输入用户名！' }]}
          >
            <Input 
              prefix={<UserOutlined />} 
              placeholder="用户名" 
              size="large"
            />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[{ required: true, message: '请输入密码！' }]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="密码"
              size="large"
            />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" block size="large">
              登录
            </Button>
          </Form.Item>
        </Form>
        <Button type="link" block onClick={() => navigate('/register')}>
          没有账号？注册
        </Button>
      </Card>
      <Modal
        title="医生注册"
        open={registerVisible}
        onCancel={() => setRegisterVisible(false)}
        footer={null}
        destroyOnClose
      >
        <Form
          form={registerForm}
          onFinish={onRegister}
          layout="vertical"
        >
          <Form.Item name="username" label="用户名" rules={[{ required: true, message: '请输入用户名！' }]}> <Input /> </Form.Item>
          <Form.Item name="password" label="密码" rules={[{ required: true, message: '请输入密码！' }]}> <Input.Password /> </Form.Item>
          <Form.Item name="confirm" label="确认密码" dependencies={["password"]} rules={[
            { required: true, message: '请确认密码！' },
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue('password') === value) {
                  return Promise.resolve();
                }
                return Promise.reject(new Error('两次输入的密码不一致！'));
              },
            }),
          ]}>
            <Input.Password />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" block>注册</Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Login; 